package com.yycx.starter.shardingjdbc.algorithm;

import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingValue;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 复合分片策略实现类
 */
public class ComplexKeyShardingImpl implements ComplexKeysShardingAlgorithm<Long> {

    public final static int GOODS_TABLE_LENGTH = 2;

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, ComplexKeysShardingValue<Long> shardingValue) {
        Long goodsId = Long.valueOf(shardingValue.getColumnNameAndShardingValuesMap().get("goods_id").toArray()[0].toString());
        for (String s : availableTargetNames) {
            int hash = this.getHash(goodsId);
            if (s.endsWith(hash + "")) {
                List<String> list = new ArrayList<>();
                list.add(s);
                return list;
            }
        }
        throw new UnsupportedOperationException();
    }

    public int getHash(Long key) {
        return key.hashCode() & (GOODS_TABLE_LENGTH - 1);
    }

    @Override
    public void init() {

    }

    @Override
    public String getType() {
        return null;
    }
}